package com.csdj.t309springboot.utils;
import org.apache.tomcat.util.buf.HexUtils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 加密工具类
 */
public class EncryptUtil {
    public static final String KEY_HMAC="HmacMD5";
    public static final String ALGO_AES = "AES";
    public static final String AES_MODEL = "AES/ECB/PKCS5Padding";
    public static final String AES_KEY = "AIEJFALHsiejfae2";

    /**
     * 传入文本内容，返回 SHA-256 串
     * @param strText
     * @return
     */
    public static String SHA256(final String strText) {
        return SHA(strText, "SHA-256");
    }

    /**
     * 传入文本内容，返回 SHA-512 串
     *
     * @param strText
     * @return
     */
    public static String SHA512(final String strText) {
        return SHA(strText, "SHA-512");
    }

    /**
     * md5加密
     * @param strText
     * @return
     */
    public String SHAMD5(String strText) {
        return SHA(strText, "MD5");
    }

    /**
     * 字符串 SHA 加密
     *
     * @param strText
     * @param strType
     * @return
     */
    private static String SHA(final String strText, final String strType) {
        // 返回值
        String strResult = null;

        // 是否是有效字符串
        if (strText != null && strText.length() > 0) {
            try {
                // SHA 加密开始
                // 创建加密对象 并傳入加密類型
                MessageDigest messageDigest = MessageDigest.getInstance(strType);
                // 传入要加密的字符串
                messageDigest.update(strText.getBytes());
                // 得到 byte 類型结果
                byte byteBuffer[] = messageDigest.digest();

                // 將 byte 轉換爲 string
                StringBuffer strHexString = new StringBuffer();
                // 遍歷 byte buffer
                for (int i = 0; i < byteBuffer.length; i++) {
                    String hex = Integer.toHexString(0xff & byteBuffer[i]);
                    if (hex.length() == 1) {
                        strHexString.append('0');
                    }
                    strHexString.append(hex);
                }
                // 得到返回結果
                strResult = strHexString.toString();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }

        return strResult;
    }
    //原文链接：https://blog.csdn.net/yushuangping/article/details/107659603


    /**
     * md5加密
     * @param str
     * @return
     */
    public static String getMd5(String str){
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("md5");
            md5.update(str.getBytes());
            byte[] digest = md5.digest();
            return HexUtils.toHexString(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getSha256(String str){
        MessageDigest sha256 = null;
        try {
            sha256 = MessageDigest.getInstance("sha256");
            sha256.update(str.getBytes());
            byte[] digest = sha256.digest();
            return HexUtils.toHexString(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String initMacKey(){
        KeyGenerator instance = null;
        try {
            instance = KeyGenerator.getInstance(KEY_HMAC);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        SecretKey secretKey = instance.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    public static String encryByHmac(String data,String secret){
        SecretKey  secretKey = new SecretKeySpec(Base64.getDecoder().decode(secret), KEY_HMAC);
        try {
            Mac instance = Mac.getInstance(KEY_HMAC);
            instance.init(secretKey);
            byte[] bytes = instance.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String encryptByAes(String data){
        Cipher instance = null;
        try {
            instance = Cipher.getInstance(AES_MODEL);
            SecretKey secretKey = new SecretKeySpec(AES_KEY.getBytes(), ALGO_AES);
            instance.init(Cipher.ENCRYPT_MODE,secretKey);
            byte[] bytes = instance.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decryptByAes(String encrypted){
        Cipher instance = null;
        try {
            instance = Cipher.getInstance(AES_MODEL);
            SecretKey secretKey = new SecretKeySpec(AES_KEY.getBytes(), ALGO_AES);
            instance.init(Cipher.DECRYPT_MODE,secretKey);
//            instance.
            byte[] bytes = instance.doFinal(Base64.getDecoder().decode(encrypted));
            return new String(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * main入口方法
     * @param args
     */
    public static void main(String[] args) {
//        System.out.println(getMd5("asdfasdfjaskdfj"));
        System.out.println("sha256加密:"+SHA256("asdfasdfjaskdfj"));
//        System.out.println("sha256加密:"+getSha256("asdfasdfjaskdfj"));

    }
}
